package cn.juque.lucenecandy.core.datasync;

import cn.juque.lucenecandy.bo.IndexUpdateParamBO;
import cn.juque.lucenecandy.core.annotation.DataSync;
import cn.juque.lucenecandy.core.constants.StrConstant;
import cn.juque.lucenecandy.helper.DocumentHelper;
import cn.juque.lucenecandy.helper.LuceneHelper;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.TermQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>DefaultDataSyncServiceImpl</li>
 * </ul>
 * @date 2024-01-04
 **/
@DataSync
@Service("defaultDataSyncService")
public class DefaultDataSyncServiceImpl implements IDataSyncService {

    @Resource
    private LuceneHelper luceneHelper;

    @Resource
    private DocumentHelper documentHelper;

    /**
     * 更新
     *
     * @param param 数据
     */
    @Override
    public void commit(IndexUpdateParamBO param) {
        switch (param.getSyncType()) {
            case ADD:
                List<Document> docList = this.documentHelper.toDocumentList(param.getContent());
                this.luceneHelper.addDocuments(param.getIndexName(), docList);
                break;
            case UPDATE:
                param.getContent().forEach(f -> {
                    BooleanQuery.Builder builder = new BooleanQuery.Builder();
                    builder.add(new TermQuery(new Term(StrConstant.D_ID, f.getId())), BooleanClause.Occur.MUST);
                    this.luceneHelper.updateByQuery(param.getIndexName(), builder.build(), this.documentHelper.toDocument(f));
                });
                break;
            case DEL:
                BooleanQuery.Builder builder = new BooleanQuery.Builder();
                param.getIdList().forEach(f -> builder.add(new TermQuery(new Term(StrConstant.D_ID, f)), BooleanClause.Occur.SHOULD));
                this.luceneHelper.deleteDocuments(param.getIndexName(), builder.build());
                break;
            default:
                break;
        }
    }

    /**
     * 删除
     *
     * @param param 数据
     */
    @Override
    public void cancel(IndexUpdateParamBO param) {
        // do nothing
    }
}
